package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(Long id) {
            carPackageAuditMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    //更新实例 ID
    @Override
    public void updateInstanceId(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateInstanceId(carPackageAudit);
    }

    //查看审核进度(查看流程图)
    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = this.get(id);
        String instanceId = carPackageAudit.getInstanceId();//审核对象 关联的 流程实例Id
        List<String> highLightedActivities =null;//高亮
        //如果状态为审核中或者审核拒绝，说明还正在流程中
        if(carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS) ){
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);//根据流程实例ID获取到当前活动节点,设置显示高亮
        }else{
            highLightedActivities = new ArrayList<>();
        }
        Long bpmnInfoId = carPackageAudit.getBpmnInfoId();
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //绘图
        return generator.generateDiagram(bpmnModel,highLightedActivities,Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    //撤销审核流程
    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "撤销审核");
    }

    @Override
    @Transactional
    //我的待办 审核
    public void audit(Long id, int auditStatus, String info) {
        //--合理性校验--
        //先判断状态
        CarPackageAudit carPackageAudit = this.get(id);
        if(carPackageAudit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        //当前登录用户是当前审核对象的审核人
        if (!ShiroUtils.getUserId().equals(carPackageAudit.getAuditorId())) {
            throw new BusinessException("只有处理人才可以对这个记录进行审核");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            info = "【"+userName+"】"+"同意,批注意见:"+info;
        }else{
            info = "【"+userName+"】"+"拒绝,批注意见:"+info;
        }
        carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+info);//设置批注
        //让Activiti中的流程往后流转
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(carPackageAudit.getInstanceId())
                .singleResult();
        //完成任务前设置流程变量
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);

        taskService.addComment(currentTask.getId(),carPackageAudit.getInstanceId(),info);
        //完成任务
        taskService.complete(currentTask.getId());
        //更新审核时间
        carPackageAudit.setAuditTime(new Date());
        //获取下一个节点
        Task nextTask = taskService.createTaskQuery()
                .processInstanceId(carPackageAudit.getInstanceId())
                .singleResult();
        //审核通过还是审核拒绝
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){//状态为审核通过
            if(nextTask!=null){//且下一个节点不为空
                //财务审核
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                carPackageAudit.setAuditTime(new Date());//审核时间
            }else{//审核通过,改变审核状态
                //流程走完,把auditorId设置为空
                carPackageAudit.setAuditorId(null);
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
        }else{//审核拒绝,改变审核状态
            //流程走完,把auditorId设置为空
            carPackageAudit.setAuditorId(null);
            //审核对象的状态改为审核拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            //服务单项审核状态改为:重新调整
            serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        }
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
